<script  lang="ts">
import { CurrencyList } from '~/components/currency';

type TCurrencyBalance = Api.GetData<typeof apis.apiFundDepositReady>['currency_balance_list'];
</script>

<script setup lang="ts">
const props = defineProps<{
  list?: TCurrencyBalance;
}>();
const currency = defineModel<string>('currency', { default: '' });
const chain = defineModel<string>('chain', { default: '' });

const currencyOptions = computed(() => props.list?.map(item => ({
  value: item.currency,
  label: item.currency,
  disabled: item.allow_deposit === 0,
})));
const chainOptions = computed(() => props.list?.find(item => item.currency === currency.value)?.tokens?.map(item => ({
  value: item.chain,
  label: `${item.chain} (${item.network})`,
  disabled: item.allow_deposit === 0,
})));

// 初始化 token
watch(currencyOptions, (val) => {
  if (val)
    currency.value = val[0].value;
}, { immediate: true });
watch(chainOptions, (val) => {
  if (val)
    chain.value = val[0].value;
}, { immediate: true });

const $currencySelect = ref<any>();

// 为了在选择币种后关闭选择框
function blurCurrencySelect() {
  $currencySelect.value?.blur?.();
  const parentEle: HTMLElement = $currencySelect.value?.$el.parentElement;
  const clickEv = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
  parentEle?.dispatchEvent(clickEv);
}

function selectCurrency(name: string) {
  if (name === currency.value)
    return;

  const currencyInfo = props.list?.find(item => item.currency === name);
  const chainInfo = currencyInfo?.tokens?.[0];

  if (!currencyInfo || !chainInfo)
    return;

  currency.value = currencyInfo.currency;
  chain.value = chainInfo.chain;
}
</script>

<template>
  <div class="flex">
    <!-- 币种 -->
    <TAntdTheme component="Select" theme="light">
      <ASelect
        ref="$currencySelect"
        :value="currency" :options="currencyOptions"
        class="w-full flex-1" :dropdownMatchSelectWidth="false"
        :getPopupContainer="(el: HTMLElement) => el.parentElement!"
      >
        <template #optionLabel="option">
          <div v-if="option" class="flex items-center">
            <TCurrencyIcon class="mr-2" :symbol="option.value" /> {{ option.label }}
          </div>
        </template>
        <template #dropdownRender>
          <CurrencyList
            :value="currency"
            class="pointer-events-auto w-60 p-1.5" listClass="max-h-45"
            :currencyList="props.list" :showConvertToFiatBtn="false"
            @update:value="selectCurrency($event ?? '')" @close="blurCurrencySelect()"
          />
        </template>
      </ASelect>
    </TAntdTheme>

    <!-- 链 -->
    <TAntdTheme component="Select" theme="light">
      <ASelect
        v-model:value="chain" :options="chainOptions"
        class="ml-3 w-full flex-1"
        :getPopupContainer="(el: HTMLElement) => el.parentElement!"
      />
    </TAntdTheme>
  </div>
</template>
